/*
 * @Author: wjc
 * @Date: 2025-10-20 15:08:38
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 17:30:39
 * @Description:
 */
import { useUserStore } from '#/stores/modules/user-store'
import createAlovaInstance from '@nice/request'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'

const Http = createAlovaInstance({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  beforeRequest: (method) => {
    const userStore = useUserStore()
    if (userStore.token) {
      method.config.headers.authorization = `Bearer ${userStore.token}`
    }
  },
  onResponseSuccess: (res) => {
    const userStore = useUserStore()
    if (res.status === 200 || res.status === 201 || res.status === 204) {
      if (
        Object.prototype.hasOwnProperty.call(res.headers, 'authorization') &&
        res.headers.authorization !== userStore.token
      ) {
        // 更新 token , 同时设置 store
        userStore.token = res.headers.authorization
      }
      return res
    }
  },
  // 全局的请求异常处理
  onResponseError: (res) => {
    switch (res.status) {
      case 401: {
        // token 失效重置
        ElMessageBox.confirm('登录已失效，请重新登录。', '温馨提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const userStore = useUserStore()
          userStore.logout()
        })
        break
      }
      case 403: {
        ElMessage({ message: '没有权限进行该操作', type: 'error', duration: 5 * 1000 })
        break
      }
      case 413: {
        ElMessage({ message: '文件太大，先压缩文件体积再尝试', type: 'error', duration: 5 * 1000 })
        break
      }
      case 422: {
        // 不作处理，由表单处处理
        break
      }
      case 503: {
        ElNotification({
          title: '提示',
          dangerouslyUseHTMLString: true,
          message: '服务不可用，请稍候再试',
          type: 'error',
          duration: 7000,
          offset: 100,
        })
        break
      }
      case 522: {
        ElNotification({
          title: '操作提示',
          message: res.message,
          type: 'error',
          duration: 5000,
          offset: 100,
        })
        break
      }
      default: {
        ElNotification({
          title: '程序运行异常',
          dangerouslyUseHTMLString: true,
          message: `${res.message}<br />已通知管理员，请稍后再试`,
          type: 'error',
          duration: 7000,
          offset: 50,
        })
        break
      }
    }
    return res
  },
})

export default Http
